package com.aliware.tianchi;

import com.aliware.tianchi.loadbalance.CustomLoadBalance;
import com.aliware.tianchi.loadbalance.RoundRobinLB;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 负载均衡扩展接口
 * 必选接口，核心接口
 * 此类可以修改实现，不可以移动类或者修改包名
 * 选手需要基于此类实现自己的负载均衡算法
 */
public class UserLoadBalance implements LoadBalance {

    private final static Logger log = LoggerFactory.getLogger(UserLoadBalance.class);

    private static CustomLoadBalance clb = new RoundRobinLB();

    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
//        log.info("负载均衡列表：{}", invokers);
//        ThreadLocalRandom.current().nextInt(invokers.size())
        int lb = clb.lb(invokers);
        log.info("结果：size:={},index={}",invokers.size(),lb);
        return invokers.get(lb);
    }
}
